"""
图像提供商工厂
根据配置动态创建不同的图像提供商实例
"""
from typing import Dict, Any
from loguru import logger

from storyforge.providers.base import ProviderBase
from storyforge.config import get_provider_config
from storyforge.providers.imagegen_x import ImageGenProvider
from storyforge.providers.image_wanxiang import ImageWanxiangProvider


class ImageProviderFactory:
    """图像提供商工厂"""

    _provider_classes: Dict[str, type] = {
        "imagegen": ImageGenProvider,     # 示例
        "wanxiang": ImageWanxiangProvider # 通义万相
    }

    @classmethod
    def register_provider(cls, provider_name: str, provider_class: type):
        if not issubclass(provider_class, ProviderBase):
            raise ValueError("提供商类必须继承自ProviderBase")
        cls._provider_classes[provider_name] = provider_class
        logger.info(f"已注册图像提供商: {provider_name}")

    @classmethod
    def create_provider(cls, provider_name: str) -> ProviderBase:
        provider_config = get_provider_config(provider_name)
        if not provider_config:
            raise ValueError(f"提供商配置不存在: {provider_name}")

        # 直接按名称映射；未匹配则尝试名称包含判断
        provider_class = cls._provider_classes.get(provider_name)
        if not provider_class:
            name_lower = provider_name.lower()
            if "wanxiang" in name_lower or "dashscope" in name_lower:
                provider_class = ImageWanxiangProvider
            else:
                provider_class = ImageGenProvider

        try:
            instance = provider_class(provider_config.dict(exclude_none=True))
            logger.debug(f"已创建图像提供商实例: {provider_name}")
            return instance
        except Exception as e:
            logger.error(f"创建图像提供商实例失败: {provider_name}, 错误: {e}")
            raise


